package org.blueoxygen.kukuruyuk.actions.item;
import java.lang.reflect.InvocationTargetException;
import java.sql.Timestamp;
import org.apache.commons.beanutils.PropertyUtils;
import org.blueoxygen.cimande.LogInformation;
import org.blueoxygen.cimande.gx.entity.GxDroplistValue;
import org.blueoxygen.kukuruyuk.entity.Item;
import org.blueoxygen.kukuruyuk.entity.Supplier;

public class SaveItem extends ItemForm{
	
	private String supplierId;
	private String dropValue;
	
	public String execute(){
		if(getItem().getName() == null ||
		"".equalsIgnoreCase(getItem().getName())){
		addActionError("Nama Item tidak boleh kosong");
		}
		
		if(getSupplierId() == null ||
				"".equalsIgnoreCase(getSupplierId())){
				addActionError("Item Supplier tidak boleh kosong");
				}
		
		if(getDropValue() == null ||
				"".equalsIgnoreCase(getDropValue())){
				addActionError("Kategori Item tidak boleh kosong");
				}
		
		if(hasErrors()){

			if(getItem().getId() != null &&
					!"".equalsIgnoreCase(getItem().getId().trim())){
					setItem((Item) manager.getById(Item.class, getItem().getId()));
			}
			setDroplistValues(manager.getList("SELECT w FROM "+GxDroplistValue.class.getName()+" w WHERE w.name.id='8a8a8a951f5fb364011f5fb4432d0001'", null, null));
		return INPUT;
		}

		LogInformation log;
		if(getItem().getId() == null || 
		"".equalsIgnoreCase(getItem().getId())){
		log = new LogInformation();
		log.setCreateBy(sessionCredentials.getCurrentUser().getId());
		log.setCreateDate(new Timestamp(System.currentTimeMillis()));
		getItem().setId(null);
		} else {
			Item temp = getItem();
		setItem((Item) manager.getById(Item.class, getItem().getId()));
		log = getItem().getLogInformation();
		try {
		PropertyUtils.copyProperties(getItem(), temp);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
		e.printStackTrace();
		} catch (NoSuchMethodException e) {
		e.printStackTrace();
		}
		}
		
		log.setLastUpdateBy(sessionCredentials.getCurrentUser().getId());
		log.setLastUpdateDate(new Timestamp(System.currentTimeMillis()));
		log.setActiveFlag(1);
		
		setSupplier((Supplier) manager.getById(Supplier.class, getSupplierId()));
		
		getItem().setLogInformation(log);
		getItem().setCategory(getDropValue());
		getItem().setSupplier(getSupplier());
	    
		manager.save(getItem());
		return SUCCESS;
		}

	public String getSupplierId() {
		return supplierId;
	}

	public void setSupplierId(String supplierId) {
		this.supplierId = supplierId;
	}

	public String getDropValue() {
		return dropValue;
	}

	public void setDropValue(String dropValue) {
		this.dropValue = dropValue;
	}
	
}
